package com.hboxs.asl.controller.app.index;

import com.hboxs.asl.JsonMessage;
import com.hboxs.asl.controller.app.BaseController;
import com.hboxs.asl.entity.Coupon;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.service.CouponService;
import com.hboxs.asl.service.MemberService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.HashSet;
import java.util.Set;

/**
 * Created by xxx on 2016/12/22
 * 首页优惠卷接口,未登录,筛选全部
 */
@Controller(value = "appCouponController")
@RequestMapping(value = "/app/coupon")
public class CouponControl extends BaseController {

    @Resource(name = "memberServiceImpl")
    private MemberService memberService;
    @Resource(name = "couponServiceImpl")
    private CouponService couponService;

    /**
     * 获取可领取优惠卷列表
     *
     * @return 优惠卷列表
     */
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public
    @ResponseBody
    Object index() {

        try {
            Set<Coupon> set;
            Member member = memberService.getCurrentByToken();
            if (member == null) {
                set = new HashSet<>(couponService.findEnableCoupons());

            } else {
                set = couponService.findReceivableCoupons(member);
            }

            return JsonMessage.success(
                    JsonMessage.optimiseObj(set,"id", "cut", "name", "maximumPrice", "endDate")
            );

        } catch (Exception e) {
            logger.error(e.getMessage(), e);
        }
        return JsonMessage.UNKNOWN_ERROR;
    }

}
